package cn.ratel.kit;

import cn.ratel.db.Model;
import com.alibaba.fastjson.JSON;

import java.util.Map;

public class JsonKit {

	public static <T> T toObject(String json, Class<T> clazz) {
		return Factory.parser.toObject(json, clazz);
	}

	public static <T> String toJson(T obj) {
		return Factory.parser.toJson(obj);
	}

	public static class Factory {
		private static Parser parser = new Parser() {

			@Override
			public <T> T toObject(String json, Class<T> clazz) {
				if (StrKit.isBlank(json)) {
					return null;
				}
				T object;
				if (Model.class.isAssignableFrom(clazz)) {
					Map<String, Object> map = JSON.parseObject(json, Map.class);
					try {
						object = clazz.newInstance();
						Model model = (Model) object;
						model.put(map);
					} catch (InstantiationException | IllegalAccessException e) {
						throw new RuntimeException("can not create instance of : " + clazz.getName(), e);
					}
				} else {
					object = JSON.parseObject(json, clazz);
				}
				return object;
			}

			@Override
			public String toJson(Object obj) {
				if (obj == null) {
					return null;
				}
				if (obj instanceof Model) {
					Model model = (Model) obj;
					return JSON.toJSONString(model.attrsColumnOnly());
				}
				return JSON.toJSONString(obj);
			}
		};

		public static void setParser(Parser parser) {
			Factory.parser = parser;
		}
	}

	public interface Parser {
		<T> T toObject(String text, Class<T> clazz);

		String toJson(Object obj);
	}

}
